package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Employee;
import com.sky.mapper.EmployeeMapper;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
	
	private EmployeeMapper employeeMapper;
	
	public JwtTokenAdminInterceptor(EmployeeMapper employeeMapper) {
		this.employeeMapper = employeeMapper;
	}
	
	/**
	 * 校验jwt
	 *
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		//判断当前拦截到的是Controller的方法还是其他资源
		if (!(handler instanceof HandlerMethod)) {
			//当前拦截到的不是动态方法，直接放行
			log.info("放行非动态方法");
			return true;
		}
		
		//DONE 修改JwtUtil.getClaimsBody抛出可能的IllegalArgumentException与NullPointerException
		Claims claims = JwtUtil.getClaimsBody(request.getHeader("token"));
		int employeeId = JwtUtil.verifyToken(claims);
		Long id = null;
		if (claims != null) {
			id = claims.get(JwtClaimsConstant.ID, Long.class);
		}
		//简单地防止一下越权
		//如果有登录数据，代表一登录，放行
		if ((employeeId == -1 || employeeId == 0) && isNotBaned(id)) {
			BaseContext.setCurrentId(id);
			return true;
		} else {
			//否则，发送未认证错误信息
			response.setStatus(401);
			return false;
		}
	}
	
	/**
	 * 检查账户活动状态
	 */
	private boolean isNotBaned(Long id) {
		Employee employee = employeeMapper.getEmpBy(null, id).remove(0);
		return Objects.equals(employee.getStatus(), StatusConstant.ENABLE);
	}
}
